<template>
  <div ref="echartsRef" :style="{ width, height }"></div>
</template>

<script>
import { onMounted, onUnmounted, ref, watch } from "vue";
import * as echarts from "echarts";

export default {
  name: "EChartsComponent",
  props: {
    option: {
      type: Object,
      required: true,
    },
    width: {
      type: String,
      default: "600px",
    },
    height: {
      type: String,
      default: "400px",
    },
  },
  setup(props) {
    const echartsRef = ref(null);
    let chartInstance = null;
    const initChart = () => {
      if (echartsRef.value) {
        chartInstance = echarts.init(echartsRef.value);
        chartInstance.setOption(props.option);
      }
    };
    onMounted(() => {
      initChart();
    });
    watch(
      () => props.option,
      (newOption) => {
        if (chartInstance) {
          chartInstance.setOption(newOption);
        }
      }
    );
    onUnmounted(() => {
      chartInstance && chartInstance.dispose();
    });
    return { echartsRef };
  },
};
</script>
